import datetime
from mongoengine import fields
from models.meta import BaseDocument, BaseEmbeddedDocument, IdField


class Result(BaseEmbeddedDocument):
    file = fields.FileField()
    file_type = fields.StringField()
    filename = fields.StringField(default='')
    status = fields.StringField(default='')
    progress = fields.IntField(min_value=0, default=0)
    created_at = fields.DateTimeField(default=None)


class TaskTargets(BaseEmbeddedDocument):
    target_url = fields.StringField(default='')
    target_id = IdField()
    target_name = fields.StringField(default='')


class Params(BaseEmbeddedDocument):
    targets = fields.ListField(fields.DictField(default={}), default=[])
    chapters = fields.ListField(fields.IntField(), default=[])
    # targets = fields.ListField(TaskTargets, default=[])
    # download_type = fields.StringField(default='')
    # report_type = fields.StringField(default='')
    start_at = fields.DateTimeField(default=None)
    end_at = fields.DateTimeField(default=None)


class CeleryTasks(BaseDocument):
    export_task_id = IdField()
    celery_task_id = fields.StringField(default='')
    task_type = fields.StringField(required=True)
    params = fields.EmbeddedDocumentField(Params, default=Params)
    result = fields.EmbeddedDocumentField(Result, default=Result)
    operator = fields.StringField(default='')
    user_id = fields.StringField(required=True)
    created_at = fields.DateTimeField(required=True)
    updated_at = fields.DateTimeField(required=True)

    meta = {
        'collection': 'scan_celery_tasks',
        'primary_key': 'export_task_id',
        'strict': False
    }

    def save(self, *args, **kwargs):
        if not self.created_at:
            self.created_at = datetime.datetime.utcnow()
        self.updated_at = datetime.datetime.utcnow()
        return super(CeleryTasks, self).save(*args, **kwargs)
